package com.example.finalwork2.handler;

import com.example.finalwork2.component.SignalRuleManager;

import com.example.finalwork2.dto.WarningInfo;
import com.example.finalwork2.entity.AlertLevel;
import com.example.finalwork2.entity.VehicleSignal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JudgeHandler extends AbstractSignalHandler {


    @Autowired
    private SignalRuleManager signalRuleManager;
//    private final SignalRuleManager signalRuleManager;
//
//    public JudgeHandler(SignalRuleManager signalRuleManager) {
//        this.signalRuleManager = signalRuleManager;
//    }

    @Override
    public void handle(VehicleSignal data) {
        String batteryType = data.getBatteryType();

        // 电压差判断
        if (data.getMx() != null && data.getMi() != null) {
            double voltageDiff = data.getMx() - data.getMi();
            List<AlertLevel> voltageRules = signalRuleManager.getRules("1", batteryType, "VoltageDiff");
            System.out.println("拿到的电压规则示例");
            System.out.println(voltageRules.get(0));
            for (AlertLevel rule : voltageRules) {
                if (voltageDiff >= rule.getMinValue() && voltageDiff < rule.getMaxValue()) {
                    WarningInfo warning = new WarningInfo();
                    warning.setVehicleId(data.getVehicleId());
                    warning.setBatteryType(batteryType);
                    warning.setWarnName("电压差报警");
                    warning.setWarnLevel(rule.getAlertLevel());
                    data.getWarnings().add(warning);
                    break; // 如果一个规则匹配到了就跳出
                }
            }
        }

        // 电流差判断
        if (data.getIx() != null && data.getIi() != null) {
            double currentDiff = data.getIx() - data.getIi();
            List<AlertLevel> currentRules = signalRuleManager.getRules("2", batteryType, "CurrentDiff");
            System.out.println("拿到的电流规则示例");
            System.out.println(currentRules.get(0));
            for (AlertLevel rule : currentRules) {
                if (currentDiff >= rule.getMinValue() && currentDiff < rule.getMaxValue()) {
                    WarningInfo warning = new WarningInfo();
                    warning.setVehicleId(data.getVehicleId());
                    warning.setBatteryType(batteryType);
                    warning.setWarnName("电流差报警");
                    warning.setWarnLevel(rule.getAlertLevel());
                    data.getWarnings().add(warning);
                    break;
                }
            }
        }

        System.out.println("预警判断完成，生成预警信息：" + data.getWarnings());

        if (next != null) {
            next.handle(data);
        }
    }


}
